package vg.modules.opener.system;


import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import vg.modules.opener.system.graphml.GraphMLDecoder;
import vg.services.data_base_manager.interfaces.IModel;
import vg.services.main_manager.MainManager;

public class SimpleOpener {
	/**
	 * This field mapped extension to decoder
	 */
	private HashMap <String,IDecoder> decoders;
	private ArrayList<String> openedFilesList;
	
	public SimpleOpener() {
		decoders = new HashMap<String, IDecoder>();
		openedFilesList = new ArrayList<String>();
		
		//register decoders TODO move this stuff into method
		decoders.put("graphml", new GraphMLDecoder());
		//decoders.put("gml", new GMLDecoder());
		decoders.put("vgdb", new VGDBDecoder());
	}

    /**
     * This method reads a graph from a graphML file into this.model
     * @param fileName - name of file to be read
     * @return - Number of read graph in the model
     * @throws CoreException
     */
	public List<Integer> openFile(String fileName, IModel model) throws Exception {    	
    	//getting decoder for file
    	 
    	String extension = fileName.toLowerCase().replaceAll(".*\\.", "");
    	
    	IDecoder decoder = decoders.get(extension);
    	if (decoder == null)
    		throw new Exception("Couldn't find decoder for *." + extension + "file");
    	String name = "Unknown";
    	int index = fileName.lastIndexOf(File.separatorChar);
    	if (index < 0) {
    		name = fileName;
    	} else {
    		name = fileName.substring(index + 1);
    	}
        Date d = new Date();

    	List<Integer> graph_id = decoder.decode(fileName, model, name.replaceFirst("\\..*$", ""));
    	if (graph_id == null || graph_id.isEmpty()) {
    		MainManager.log.printError("[" + this.getClass().getName() + ".openGraph] [BAD] Cannot to add graph in model.");
    		throw new Exception("Cannot to add graph in model.");
    	}
    	openedFilesList.add(fileName);
    	MainManager.log.printInfo("Graph load time: " + (new Date().getTime() - d.getTime()) / 1000.0 + "sec");
    	return graph_id;
	}

	public Set<String> getAvailableExtension() {
		if (decoders != null)
			return decoders.keySet();
		else 
			return null;
	}
	public List<String> getOpenedFilesList() {
		return openedFilesList;
	}
}
